<template>
  <div class="merak-container-has-search">
    <SearchBar
      ref="searchBarRef"
      :placeholder="$t('goods_attribute.property_search')"
      v-model="searchData"
      @searchEvent="handleSearchEvent"
    >
      <template #footer>
        <el-button v-if="!!props.treeSelected" v-auth="{ authArr: auth, key: 'add' }" type="primary" @click="emit('add')">
          {{ $t("goods_attribute.add_clearance") }}
        </el-button>
        <el-button v-auth="{ authArr: auth, key: 'add' }" type="primary" plain @click="copyState.visible = true">
          {{ $t("goods_attribute.copy_cc_goods_property") }}
        </el-button>
      </template>
      <template #searchForm>
        <div class="modal-content">
          <div class="modal-title"></div>
          <div class="modal—body">
            <el-scrollbar class="search_from_scrollbar">
              <div class="scrollbar-content">
                <SelectedParams v-model="searchData" />
                <ClearanceSearchForm ref="searchRef" v-model="searchData" :type="props.type" :formValue="searchFormValue" />
              </div>
            </el-scrollbar>
          </div>
          <div class="modal-footer">
            <el-button type="default" @click="handleResetSearch">{{ $t("merak.reset") }}</el-button>
            <el-button type="primary" @click="handleSearch">{{ $t("merak.search") }}</el-button>
            <el-button plain type="primary" @click="searchBarRef?.showPlanModal">{{ $t("merak.save_search_scheme") }}</el-button>
          </div>
        </div>
      </template>
    </SearchBar>
    <div class="merak-table-wrapper">
      <MerakXTable
        ref="tableRef"
        v-bind="tableState"
        :handles="tableHandler"
        :enabled-editor="tableEditorAuth"
        :params="tableParams"
        :await-params="!props.lazy"
        :query-columns="handleQueryColumns"
        :query-data="handleQueryData"
        :handler-click="handleHandlerClick"
        @editor-click="handleEditorClick"
      >
        <template #custom_handle="{ row }">
          <el-button
            type="primary"
            link
            @click="
              router.push({
                name: 'archiveDetail',
                query: {
                  type: props.type,
                  prop_id: row?.cc_prop_id,
                  name: language === 'zh' ? row.cc_property_cn : row.cc_property
                }
              })
            "
          >
            {{ $t("merak.detail") }}
          </el-button>
        </template>
      </MerakXTable>
    </div>
    <EditorModal
      v-model="editorState.visible"
      v-bind="{ ...editorState.correlation, ...editorState.props }"
      @update="tableRef?.updateCell"
    />
    <EnumDrawer v-model="enumState.visible" v-bind="{ ...enumState.correlation, ...enumState.props }" />
    <CopyDrawer
      v-model="copyState.visible"
      v-bind="copyState.correlation"
      :title="$t('goods_attribute.copy_cc_goods_property')"
    />
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, inject, ref, reactive, computed, watch, onMounted } from "vue";

import { useRouter } from "vue-router";

import { ElMessage, ElButton } from "element-plus";

import { useGlobalStore } from "@/stores/modules/global";

import SearchBar from "@/components/SearchBar/index.vue";
import SelectedParams from "@/components/SearchBar/components/selectedParams.vue";

import MerakXTable, {
  MerakXTableInstance,
  MerakXTableProps,
  MerakXTableEditorParams,
  MerakXTableDropdown
} from "@/components/MerakXTable";

import { ClearanceData } from "../searchData";
import ClearanceSearchForm from "./ClearanceSearchForm.vue";
import EditorModal from "./EditorModal.vue";
import EnumDrawer, { EnumPropsType } from "./EnumDrawer.vue";
import CopyDrawer from "./CopyDrawer.vue";

import { ResultEnum } from "@/enums/httpEnum";
import { getTableColumns, getTableData } from "@/api/modules/table";
import {
  RouteType,
  TabType,
  OptionType,
  StandOptionType,
  ClearanceHeaderPath,
  ClearanceTablePath,
  deleteClearanceProperty,
  getClearanceOptions,
  getProductTypeByClearance
} from "@/api/modules/goodsArchive/allocation";

import { confirmWarningMsg } from "@/utils/messageUtils";

const props = defineProps<{
  type: RouteType;
  queueId?: string;
  treeSelected?: string;
  lazy?: boolean;
}>();

const emit = defineEmits<{
  add: [propId?: string | number];
}>();

const router = useRouter();

const { language } = useGlobalStore();

const currentInstance = getCurrentInstance();

// 注入顶层权限
const auth = inject<any>("auth");

const searchBarRef = ref<InstanceType<typeof SearchBar>>();

const searchRef = ref<InstanceType<typeof ClearanceSearchForm>>();

const tableRef = ref<MerakXTableInstance>();

// 高级搜索数据
const searchData = reactive({ ...ClearanceData });

// 高级搜索相关属性
const searchState = reactive<{
  type: RouteType;
  tableId?: string;
  search?: any;
  params?: Record<string, any>;
}>({
  type: props.type
});

// 表格相关属性
const tableState = reactive<MerakXTableProps>({
  columnsByStore: [],
  enabledEditor: true,
  rowKey: "cc_prop_id",
  columnType: [{ type: "handle", width: 130, showHandleDropDown: true, slot: "custom_handle" }]
});

// 编辑相关属性
const editorState = reactive<{
  visible: boolean;
  correlation: {
    type: RouteType;
    tab: TabType;
    typeOptions: OptionType[];
    groupOptions: OptionType[];
  };
  props?: MerakXTableEditorParams;
}>({
  visible: false,
  correlation: {
    type: props.type,
    tab: TabType.clearance,
    typeOptions: [],
    groupOptions: []
  }
});

// 枚举相关属性
const enumState = reactive<{
  visible: boolean;
  correlation: {
    type: RouteType;
    tab: TabType;
  };
  props?: EnumPropsType;
}>({
  visible: false,
  correlation: {
    type: props.type,
    tab: TabType.clearance
  }
});

// 复制相关属性
const copyState = reactive<{
  visible: boolean;
  correlation: {
    type: RouteType;
    tab: TabType;
    options: StandOptionType[];
  };
}>({
  visible: false,
  correlation: {
    type: props.type,
    tab: TabType.clearance,
    options: []
  }
});

// 给予高级搜索表单验证的值
const searchFormValue = computed(() => {
  const value: Record<string, any> = {};
  Object.keys(searchData).forEach(key => {
    value[key] = searchData[key].value;
  });
  return value;
});

// 给予表格操作权限
const tableHandler = computed(() => {
  const handles: MerakXTableDropdown[] = [
    {
      type: "enum",
      text: currentInstance?.proxy?.$t("merak.enum_value"),
      disabled: row => !["radio", "checkbox", "dropdown", "multiselect"].includes(row.cc_prop_type_val)
    }
  ];
  if (!!auth.add?.show) {
    handles.push({ type: "copy", text: currentInstance?.proxy?.$t("merak.copy") });
  }
  if (!!auth.delete?.show) {
    handles.push({
      type: "delete",
      text: currentInstance?.proxy?.$t("merak.delete"),
      color: "red",
      disabled: row => !!row.is_disable
    });
  }
  return handles;
});

// 给予表格编辑权限
const tableEditorAuth = computed(() => {
  let flag = false;
  if (!!auth?.edit?.show) {
    flag = true;
  }
  return flag;
});

// 给予表格搜索参数
const tableParams = computed(() => {
  const params: Record<string, any> = {};
  if (!!props.treeSelected) {
    params.type_id = props.treeSelected;
  }
  if (!!searchState.search) {
    params.key_words = searchState.search;
  }
  if (!!searchState.params) {
    Object.assign(params, searchState.params);
  }
  return params;
});

// 高级搜索
const handleSearchEvent = (params: { search: any; params: Record<string, any> }) => {
  const payload: Record<string, any> = {};
  searchState.search = params.search;
  Object.keys(params.params).forEach(key => {
    if (!key.includes("_options")) {
      payload[key] = params.params[key];
    }
  });
  searchState.params = payload;
};
const handleResetSearch = () => {
  searchRef.value?.reset();
};
const handleSearch = () => {
  searchRef.value?.valid()?.then(() => {
    searchState.search = undefined;
    searchState.params = { ...searchFormValue.value };
    // 清空外部搜索
    searchBarRef.value?.clear();
    // 关闭高级搜索弹窗
    searchBarRef.value?.modalHide();
  });
};

// 请求表头
const handleQueryColumns: MerakXTableProps["queryColumns"] = async () => {
  return getTableColumns(ClearanceHeaderPath[props.type], props.queueId).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      // 存储表格ID
      searchState.tableId = data.table_id;
      // 高级搜索获取搜索方案
      searchBarRef.value?.getPlanList(data.table_id);
      // 克隆表头数据作为列设置的对照数据
      tableState.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      return {
        ...data,
        columns: [...data.columns].map(column => {
          switch (column.field) {
            case "cc_prop_id":
            case "type_id":
            case "cc_property_en":
              // 唯一 key 不允许字段编辑
              return { ...column, params: { editor: false } };
            case "sort":
            case "cc_prop_group_sort":
              // 排序
              return { ...column, sortable: true };
            // case "cc_is_required":
            // case "is_spec":
            // case "is_number":
            // case "un_editable_checked":
            //   // 自定义渲染
            //   return {
            //     ...column,
            //     slots: { default: ({ row }) => (row[column.field!] === 0 ? "否" : row[column.field!] === 1 ? "是" : null) }
            //   };
            default:
              return { ...column };
          }
        })
      };
    }
  });
};

// 请求表格
const handleQueryData: MerakXTableProps["queryData"] = async ({ page, sort, from }) => {
  const params: Record<string, any> = {};
  if (!!page) {
    Object.assign(params, page);
  }
  // 如果有排序数据
  if (!!sort) {
    params.sort = sort.order === "desc" ? `-${sort.field}` : sort.field;
  }
  if (!!from) {
    Object.assign(params, from);
  }
  return getTableData(ClearanceTablePath[props.type], params, props.queueId).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      return data.table_data;
    }
  });
};

// 表格编辑事件
const handleEditorClick: MerakXTableInstance["onEditor-click"] = params => {
  editorState.props = params;
  editorState.visible = true;
};

// 操作列下拉选项点击事件
const handleHandlerClick: MerakXTableProps["handlerClick"] = async ({ type, params }) => {
  const propId = params.row?.[tableState.rowKey!];
  const typeId = params.row?.type_id_val;
  if (typeof propId === "undefined" || typeof typeId === "undefined") return;
  switch (type) {
    case "enum":
      enumState.props = {
        propId,
        typeId,
        title: language === "zh" ? params.row?.cc_property_cn : params.row?.cc_property
      };
      enumState.visible = true;
      break;
    case "copy":
      emit("add", propId);
      break;
    case "delete":
      confirmWarningMsg({
        msg: currentInstance?.proxy?.$t("goods_attribute.delete_property_message") ?? "",
        callback: (status: string) => {
          if (status === "confirm") {
            deleteClearanceProperty(props.type, propId, typeId).then(({ code, message }) => {
              if (code == ResultEnum.SUCCESS) {
                tableRef.value?.reloadData();
                ElMessage.success(currentInstance?.proxy?.$t("goods_attribute.delete_property_success"));
              } else {
                const msg = typeof message === "string" ? message : Object.values(message)?.[0];
                ElMessage.error(msg);
              }
            });
          }
        }
      });
      break;
    default:
      break;
  }
};

watch(
  () => props.treeSelected,
  () => {
    searchState.search = undefined;
    searchState.params = undefined;
    searchRef.value?.reset();
    searchBarRef.value?.clear();
  }
);

onMounted(() => {
  // 获取属性类型下拉选项
  getClearanceOptions("cc_prop_type").then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      editorState.correlation.typeOptions = data;
      searchData.cc_prop_type.options = data.map(option => ({ value: option.key, label: option.value }));
    }
  });
  // 获取属性分组下拉选项
  getClearanceOptions("cc_prop_group").then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      editorState.correlation.groupOptions = data;
      searchData.cc_prop_group.options = data.map(option => ({ value: option.key, label: option.value }));
    }
  });
  // 获取商品类型
  getProductTypeByClearance(props.type).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      copyState.correlation.options = data;
    }
  });
});

defineExpose({
  onReload: () => tableRef.value?.reloadData()
});
</script>
